#region Imported Namespaces
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;

using BO = PHSRAG.Insight21.BusinessObjects;
using Utility = PHSRAG.Utility;
using ICachePolicy = PHSRAG.Insight21.Policy.ICachePolicy;
using DataAccess = PHSRAG.Utility.DataAccess;
using System.Reflection;
#endregion

namespace PHSRAG.Insight21.CDS
{
    /// <summary>
    /// EMailTemplate
    /// </summary>
    public class EMailTemplate : BO.SmartBusinessObject
    {
        #region Constants
        private const string emailKey = "EMail_A856A922-D1C2-4e28-8F7D-C79E4882DB32";
        private const string ColumnId = "Id";
        private const string ColumnType = "Type";
        private const string ColumnBodyText = "BodyText";
        private const string ColumnSubject = "Subject";
        private const string ColumnTo = "To";
        private const string ColumnFrom = "From";
        private const string ColumnModule = "ModuleType";
        #endregion

        #region Instance Variables
        private string type;
        private string bodyText;
        private string module;
        private string subject;
        private string to;
        private string from;
        #endregion

        #region Statics
        /// <summary>
        /// Key used to place and/or retrieve this object from the cache.
        /// </summary>
        public static string EMailKey
        {
            get { return emailKey; }
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the type of the mail template
        /// </summary>
        public string Type
        {
            get { return type; }
            set { SetDirty(ref type, value); }
        }


        /// <summary>
        /// Gets or sets the text for the mail template
        /// </summary>
        public string BodyText
        {
            get { return bodyText; }
            set { SetDirty(ref bodyText, value); }
        }

        /// <summary>
        /// Gets or sets the module for the mail template
        /// </summary>
        public string Module
        {
            get { return module; }
            set { module = value; }
        }

        /// <summary>
        /// Gets or sets the subject for the mail template
        /// </summary>
        public string Subject
        {
            get { return subject; }
            set { subject = value; }
        }

        /// <summary>
        /// Gets or sets the recipient for the mail template
        /// </summary>
        public string To
        {
            get { return to; }
            set { to = value; }
        }

        /// <summary>
        /// Gets or sets the sender for the mail template
        /// </summary>
        public string From
        {
            get { return from; }
            set { from = value; }
        }
        #endregion

        #region Constructor
        /// <summary>
        /// Initilize the base class with the specified cache policy.
        /// </summary>
        /// <param name="cachePolicy">Prevalent cache policy</param>
        public EMailTemplate(ICachePolicy cachePolicy)
            : base(cachePolicy)
        {
            Module = BusinessObjects.ModuleKey.Humans;
        }
        #endregion

        public void Archive(string PIEmail, string fromEmail, string subject, string smtpServer, string connectionString)
        {
            SqlConnection connection = new SqlConnection(connectionString);

            // create a connection and open it.
            connection.Open();

            // create a transaction on the connection to be passed around.
            SqlTransaction transaction = connection.BeginTransaction(Assembly.GetExecutingAssembly().GetName().Name);

            try
            {
                // call Save method.
                SqlParameter[] paramArray = DataAccess.BuildSqlParameterArray(
                        "@to", SqlDbType.VarChar, PIEmail,
                        "@from", SqlDbType.VarChar, fromEmail,
                        "@subject", SqlDbType.VarChar, subject,
                        "@bodyText", SqlDbType.VarChar, String.IsNullOrEmpty(bodyText) ? DBNull.Value : (object)bodyText,
                        "@smtpServer", SqlDbType.VarChar, smtpServer);

                Id = Convert.ToInt32(DataAccess.ExecuteScalar(transaction.Connection, transaction, "ArchiveEMail",
                    paramArray));

                // commit the SQL transaction.
                transaction.Commit();
            }
            catch
            {
                // rollback the transaction if it exists.
                if (transaction != null)
                {
                    transaction.Rollback();
                }
                throw;
            }
            finally
            {

                // do some cleanup.
                if (connection.State != ConnectionState.Closed)
                    connection.Close();
            }

        }

        #region SmartBusinessObject methods
        /// <summary>
        /// Cache Key uniquely identifies this object within the cache.
        /// </summary>
        /// <returns>the unique string for this object.</returns>
        public override string CacheKey()
        {
            return emailKey;
        }


        /// <summary>
        /// Cache this instance using the prevalent cache policy.
        /// </summary>
        public override void Cache()
        {
            CachePolicy.Cache(emailKey, this);
        }


        /// <summary>
        /// Remove this instance from the cache using the prevalent cache policy.
        /// </summary>
        public override void UnCache()
        {
            CachePolicy.UnCache(emailKey);
        }


        /// <summary>
        /// Loads the EMailTemplate object with the specified id.
        /// </summary>
        /// <param name="connectionString">Information to connect to the database</param>
        /// <param name="args">Id of the document to be loaded</param>
        public override void Load(string connectionString, params object[] args)
        {
            if (args.Length < 1)
                throw new Exception("EMailTemplate Load expects type");
            else
                Type = args[0].ToString();
            
            if (args.Length == 2)
                Module = args[1].ToString();

            DataSet mailTemplateDetails = Utility.DataAccess.GetDataSet(connectionString, "GetEMailTemplate",
                Utility.DataAccess.BuildSqlParameterArray("@type", SqlDbType.VarChar, Type,
                "@moduleType", SqlDbType.VarChar, Module));

            DataRowCollection rows = mailTemplateDetails.Tables[0].Rows;
            if (rows.Count > 0)
                PopulateMembers(rows[0]);
            else
                throw new ApplicationException(string.Format("No email template found for type: {0}, module: {1}", Type, Module));
        }


        /// <summary>
        /// Saves the state of the EMailTemplate object to the database. 
        /// The stored procedure inserts a new record if the id of the object is 0, 
        /// otherwise the procedure updates the record with the matching email template id
        /// </summary>
        /// <param name="sqlTransaction">The context in which the insert/update should be executed</param>
        protected override void SaveObject(System.Data.SqlClient.SqlTransaction sqlTransaction)
        {
            SqlParameter[] paramArray = DataAccess.BuildSqlParameterArray(
                "@id", SqlDbType.Int, Id,
                "@type", SqlDbType.VarChar, type,
                "@bodyText", SqlDbType.VarChar, String.IsNullOrEmpty(bodyText) ? DBNull.Value : (object)BodyText,
                "@moduleType", SqlDbType.VarChar, Module,
				"@subject",SqlDbType.VarChar,(subject == string.Empty) ? DBNull.Value : (object)Subject,
                "@to", SqlDbType.VarChar, (To == string.Empty) ? DBNull.Value : (object)To,
                "@from", SqlDbType.VarChar, (From == string.Empty) ? DBNull.Value : (object)From);

            Id = Convert.ToInt32(DataAccess.ExecuteScalar(sqlTransaction.Connection, sqlTransaction, "SaveEMailTemplate",
                paramArray));
        }


        /// <summary>
        /// Deletes the mail template from the database.
        /// </summary>
        /// <param name="sqlTransaction">The transaction context in which the SQL statement is to be executed</param>
        protected override void DeleteObject(System.Data.SqlClient.SqlTransaction sqlTransaction)
        {
            throw new Exception("This method is not yet implemented");
        }

        #endregion


        #region Private methods
        /// <summary>
        /// Populates instance fields with corresponding values in the datarow
        /// </summary>
        /// <param name="dataRow">DataRow holding the values to be assigned to instance variables</param>
        private void PopulateMembers(DataRow dataRow)
        {
            Id = (int)dataRow[ColumnId];
            type = (string)dataRow[ColumnType];

            Object dbValue = dataRow[ColumnBodyText];
            bodyText = (dbValue == DBNull.Value) ? string.Empty : (string)dbValue;

            object o = dataRow[ColumnSubject];
            Subject = (o == DBNull.Value) ? string.Empty : o.ToString();

            o = dataRow[ColumnTo];
            To = (o == DBNull.Value) ? string.Empty : o.ToString();

            o = dataRow[ColumnFrom];
            From = (o == DBNull.Value) ? string.Empty : o.ToString();
        }
        #endregion

    }
}

